package com.martin.define;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;

/**
 * @author created by Martin
 * @package com.martin.define
 * @fileName MtIntentService
 * @date 2018/12/5 0005 下午 6:21
 * @describe TODO
 */
public class MtIntentService extends IntentService {

    private LocalBroadcastManager localBroadcastManager;
    public MtIntentService() {
        super("MtIntentService");
    }

    private int count = 0;

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        try{
            sendThreadStatus("线程启动", count);
            Thread.sleep(1000);
            sendServiceStatus("服务运行中");
            while(true){
                count++;
                if (count > 100)
                    break;
                sendThreadStatus("线程运行中", count);
                Thread.sleep(50);
            }
            sendThreadStatus("线程结束", count);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        sendServiceStatus("服务启动");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sendServiceStatus("服务结束");
    }

    private void sendServiceStatus(String status){
        Intent intent = new Intent(ACTION_TYPE_SERVICE);
        intent.putExtra(KEY_STATUS, status);
        localBroadcastManager.sendBroadcast(intent);
    }

    public static final String ACTION_TYPE_SERVICE = "action.service";
    public static final String ACTION_TYPE_THREAD = "action.thread";

    public static final String KEY_STATUS = "status";
    public static final String KEY_PROGRESS = "progress";

    private void sendThreadStatus(String status, int progress){
        Intent intent = new Intent(ACTION_TYPE_THREAD);
        intent.putExtra(KEY_STATUS, status);
        intent.putExtra(KEY_PROGRESS, progress);
        localBroadcastManager.sendBroadcast(intent);
    }
}
